﻿using OpcUaHelper;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;

namespace FPSO.HMI
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        /// <summary>
        /// 全局登录状态，0：普通用户，1：管理员用户
        /// </summary>
        public int LoginStatus { get; set; }

        /// <summary>
        /// 登录用户
        /// </summary>
        public string LoginUser { get; set; }

		private static OpcUaClient uaClient;
		public static OpcUaClient UaClient
		{
			get
			{
				return uaClient;
			}
			set
			{
				uaClient = value;
			}
		}

		public App()
		{
			Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;
			AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
			TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
			Exit += App_Exit;
		}

		private void App_Exit(object sender, ExitEventArgs e)
		{
			if (App.uaClient != null)
			{
				uaClient.Disconnect();
				uaClient = null;
			}
		}

		/// <summary>
		/// UI线程上未捕获的异常
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
		{
			//MessageWindow.ShowMsg("我们很抱歉，当前应用程序遇到一些问题.." + e.Exception + "意外的操作", false);
			//Common.WriteLog.Error("未捕获到的UI线程异常!", e.Exception);
			e.Handled = true;
		}

		/// <summary>
		/// 捕获应用程序域中发生的异常
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
		{
			//Common.WriteLog.Error("未捕获到的非UI线程异常!", (System.Exception)e.ExceptionObject);
			double a = 0;
		}

		/// <summary>
		/// 当出错的任务的未观察到的异常将要触发异常升级策略时发生，默认情况下，这将终止进程。
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
		{
			//Common.WriteLog.Error("未捕获到的Task任务异常!", e.Exception);
			e.SetObserved();
		}
	}
}
